package com.heima.search.listen;


import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.feigns.ArticleFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ArticleAddOrRemoveListener {

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ArticleSearchService articleSearchService;


    @RabbitListener(queuesToDeclare = @Queue(value = NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE))
    public void addArticle(String articleId){
        log.info("搜索微服务 接收添加文章的索引消息  ==>{}" , articleId);
        //远程调用feign 查询文章信息
        ResponseResult<SearchArticleVO> result = articleFeign.findArticle(Long.valueOf(articleId));
        if (result.getCode() != 0){
            log.error("索引库添加失败 远程调用文章信息失败   文章id: {}",articleId);
        }
        //获取es对应的对象
        SearchArticleVO searchArticleVO = result.getData();
        if (searchArticleVO == null){
            log.error("索引库添加失败 未获取到对应文章信息   文章id: {}",articleId);
        }

        try {
            articleSearchService.saveArticle(searchArticleVO);
            log.info("成功更新索引信息   add: {}",articleId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息消费确认失败   文章id: {}  原因: {}",articleId,e.getMessage());
        }
    }


    @RabbitListener(queuesToDeclare = @Queue(value = NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE))
    public void downArticle(String articleId){
        log.info("搜索微服务 接收到删除索引库文章消息==> {}",articleId);
        try {
            articleSearchService.deleteArticle(articleId);
            log.info("成功更新索引信息   delete: {}",articleId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息消费确认失败   文章id: {}  原因: {}",articleId,e.getMessage());
        }
    }
}

















